package cn.flying.cloud.base.common.validate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import cn.flying.cloud.base.common.enums.BaseEnumInfo;

/**
 * 自定义枚举校验器
 *
 * @author: admin
 * @date: 2023年01月31日 22:03
 * @version: 1.0
 */
public class EnumValueConstrainValidator implements ConstraintValidator<EnumVal, Object> {

    private Class<? extends BaseEnumInfo> clazz;

    /**
     * 初始化方法
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(EnumVal constraintAnnotation) {
        clazz = constraintAnnotation.value();
    }

    /**
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        BaseEnumInfo[] enumInfos = clazz.getEnumConstants();
        for (BaseEnumInfo enumInfo : enumInfos) {
            if (enumInfo.getCode().equals(value)) {
                return true;
            }
        }
        return false;
    }
}
